package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.adpter.ArticleAdapter;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.JSONUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Request;


/**
 * 健康宣教列表页面
 * Created by gaoge on 2016/11/8.
 */

public class EducationListActivity extends BaseActivity implements View.OnClickListener, MyListView.IXListViewListener {
    //标题文字
    private TextView title_name = null;
    //返回键
    private ImageView img_back = null;
    //显示数据的listview
    private MyListView listview = null;
    //listview适配器
    private ArticleAdapter articleAdapter = null;
    //无数据显示页面
    private LinearLayout no_data_linearlayout = null;
    //分类ID
    private String classifyID = "";
    //标题name
    private String name = "";
    //数据总量
    private int totalCount = 0;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number = 10;
    //保存数据集合
    private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    //加载框
    AlertDialog zhuce_dialog;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_education_list);
        //初始化组件
        initialization();
        //实现
        realize();
    }

    /**
     * 初始化组件，给相应组件添加点击事件
     */
    private void initialization() {
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();

        no_data_linearlayout = (LinearLayout) findViewById(R.id.no_data_linearlayout);
        title_name = (TextView) findViewById(R.id.title_name);
        img_back = (ImageView) findViewById(R.id.img_back);
        listview = (MyListView) findViewById(R.id.listview);
        Intent intent = getIntent();
        //获取标题，设置标题
        name = intent.getStringExtra("name");
        title_name.setText(name);
        //获取当前分类ID
        classifyID = intent.getStringExtra("id");
        img_back.setOnClickListener(this);
        //listview添加单击事件
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(EducationListActivity.this, EducationDetailsActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("id", list.get(i).get("id"));
                intent.putExtra("name", name);
                intent.putExtra("title", list.get(i).get("title"));
                intent.putExtra("content", list.get(i).get("shortDescription"));
                intent.putExtra("pic", list.get(i).get("pictureUrl"));
                startActivity(intent);
            }
        });

        articleAdapter = new ArticleAdapter(EducationListActivity.this, list, imageLoader, options);
        listview.setAdapter(articleAdapter);
    }

    /**
     * 功能实现
     */
    private void realize() {

        //获取列表数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            zhuce_dialog = new MyAlertDialog().ShowDialog(EducationListActivity.this, R.layout.dialog_loading);
            zhuce_dialog.setCancelable(true);

            getListData();
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //返回键
            case R.id.img_back:
                finish();
                break;
        }
    }

    /**
     * 下载列表数据
     */
    public void getListData() {
        HttpUtil.getData(APIMethod.EducationList(classifyID, currentPage, number), handler, new HttpUtil.OnGetDataListener() {
            @Override
            public void onJsonData(String data) {
                try {
                    String bodys = data;
                    if (bodys != null && bodys.length() > 0) {
                        JSONObject jsonObject = new JSONObject(bodys);
                        //获取数据总量
                        if (totalCount == 0) {
                            totalCount = Integer.parseInt(jsonObject.get("totalCount").toString());
                        }
                        bodys = jsonObject.get("items").toString();
                        if (bodys != null && !bodys.equals("") && !bodys.equals("[]")) {
                            onLoad();
                            JSONArray jsonArray = new JSONArray(bodys);
                            list.addAll(JSONUtil.jsonAryToListMap(jsonArray));
                            listview.setPullLoadEnable(true);
                            listview.setXListViewListener(EducationListActivity.this, totalCount, currentPage, number);
                            if(listview.getVisibility()==View.GONE){
                                listview.setVisibility(MyListView.VISIBLE);
                            }
                            if(no_data_linearlayout.getVisibility()==View.VISIBLE){
                                no_data_linearlayout.setVisibility(MyListView.GONE);
                            }
                            articleAdapter.getData(list);
                        } else {
                            loginHandler.sendEmptyMessage(2);
                        }

                    } else {
                        loginHandler.sendEmptyMessage(2);
                    }
                    if (zhuce_dialog != null) {
                        zhuce_dialog.dismiss();
                    }
                } catch (Exception e) {
                    if (zhuce_dialog != null) {
                        zhuce_dialog.dismiss();
                    }
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取线程返回的数据，更新UI组件
     */
    @SuppressLint("HandlerLeak")
    Handler loginHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (zhuce_dialog != null) {
                zhuce_dialog.dismiss();
            }
            try {
                switch (msg.what) {
                    case 1:

                        break;
                    case 2:
                        no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
                        listview.setVisibility(MyListView.GONE);
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    //上拉加载更多
    @Override
    public void onLoadMore() {
        if (totalCount > currentPage * number) {
            currentPage = currentPage + 1;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(AppConstant.THREAD_SLEEP);
                        getListData();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            onLoad();
        }
    }

    @SuppressLint("SimpleDateFormat")
    private void onLoad() {
        listview.stopLoadMore();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}
